/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package operation.teacher;

import entities.School;
import entities.Student;
import entities.TeacherAdmin;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import sessionBeans.SchoolFacadeLocal;
import sessionBeans.StudentFacadeLocal;
import sessionBeans.TeacherAdminFacadeLocal;
import tools.StaticFields;

/**
 *
 * @author HgsPc
 */
@Named
@SessionScoped
public class TeacherBean implements java.io.Serializable {

    @EJB
    private StudentFacadeLocal studentFacadeLocal;
    @EJB
    private TeacherAdminFacadeLocal teacherAdminFacadeLocal;
    @EJB
    private SchoolFacadeLocal schoolFacadeLocal;
    @Inject
    private TeaCheckLogin checkLogin;
    private String userno;
    private int cityId1;
    private Part excelFile1;
    private List<Student> student1;
    private List<TeacherAdmin> teacherList;
    private String schoolId1;
    private String studentname1;
    private String schoolId;
    private int myro[];
    private String successStudentNums;
    private final int columnNum = 5;


    public String importStudent(String schoolId) {
        if (null == schoolId || "null".equals(schoolId)) {
            FacesContext.getCurrentInstance().addMessage("OK", new FacesMessage(StaticFields.MESSAGES_PROPTES.getString("schoolSelection")));
            return null;
        }
        if (null == this.excelFile1 || this.getFilename(excelFile1).trim().length() == 0) {
            FacesContext.getCurrentInstance().addMessage("OK", new FacesMessage(StaticFields.MESSAGES_PROPTES.getString("excelSelection")));
            return null;
        }
        this.schoolId1 = schoolId;
        try {
            InputStream ins = excelFile1.getInputStream();
            Workbook book = Workbook.getWorkbook(ins);
            Sheet sheet = book.getSheet(0);
            int columnum = sheet.getColumns();//得到列数  
            int rownum = sheet.getRows();//得到行数
            if (columnum != columnNum) {
                String tem = StaticFields.MESSAGES_PROPTES.getString("excelSelection");
                tem = tem.replace("{0}", String.valueOf(columnNum));
                FacesContext.getCurrentInstance().addMessage("OK", new FacesMessage(tem));
            } else {
                int i = 1;
                successStudentNums = "";
                for (; i < rownum; i++) {
                    School sessionSchool = schoolFacadeLocal.find(((HttpSession) (FacesContext.getCurrentInstance().getExternalContext().getSession(true))).getAttribute(StaticFields.SESSION_SCHOOL_ID));
                    String SchoolId = "," + sessionSchool.getId();//学校编号
                    String StudentIdInSchool = "'" + sheet.getCell(0, i).getContents() + "',";//学生的学号
                    String password = "'" + sheet.getCell(1, i).getContents() + "',";
                    String NAME = "'" + sheet.getCell(2, i).getContents() + "',";
                    String EMAIL = "'" + sheet.getCell(3, i).getContents() + "',";
                    String PHONE = "'" + sheet.getCell(4, i).getContents() + "',";
                    String ROLEID = StaticFields.STUDENT_ROLE + ",";
                    String sqlString = "INSERT INTO STUDENT (StudentIdInSchool, PASSWORD, NAME, EMAIL, PHONE, ROLEID, school_id) VALUES (" + StudentIdInSchool + password + NAME + EMAIL + PHONE + ROLEID + SchoolId + ")";
                    this.studentFacadeLocal.executUpdate(sqlString);
                    successStudentNums = successStudentNums + StudentIdInSchool;
                }
            }
        } catch (BiffException | IOException ex) {
            FacesContext.getCurrentInstance().addMessage("OK", new FacesMessage("导入出错了，请检查excel是否存在问题！"));
        }
        return null;
    }

    private String getFilename(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }

    public void setStudent(List<Student> student) {
        this.student1 = student;
    }

    public void save(String nuo, String nameofunit, String parNameofunit) {
    }

    public String getUserno() {
        return userno;
    }

    public void setUserno(String userno) {
        this.userno = userno;
    }

    public int getCityId() {
        return cityId1;
    }

    public void setCityId(int cityId) {
        this.cityId1 = cityId;
    }

    public Part getExcelFile() {
        return excelFile1;
    }

    public void setExcelFile(Part excelFile) {
        this.excelFile1 = excelFile;
    }

    /**
     * @return the student
     */
    public List<Student> getStudent() {
        if (null != this.schoolId) {
            student1 = studentFacadeLocal.getQueryResultList("select * from student where school_id ='" + schoolId + "'");
        }
        return student1;
    }

    public void save(String uno, String schoolId) {
        this.studentFacadeLocal.executUpdate("update student set school_id='" + schoolId + "' where id=" + Integer.parseInt(uno));

    }

    public String saveTeacher(String id, int roleId, String nameofUnitId) {
        this.teacherAdminFacadeLocal.executUpdate("update teacher_admin set role_id=" + roleId + "' where id=" + id);//",nameofunitId='" + nameofUnitId + 
        return null;
    }

    public String direct2BackupImport() {
        return "importStudent";
    }
    /**
     * @return the schoolId //
     */
    public String getSchoolId() {
        return schoolId1;
    }

    /**
     * @param schoolId the schoolId to set
     */
    public void setSchoolId(String schoolId) {
        this.schoolId1 = schoolId;
    }

    public String addStudent() {
        //Need to Do
        System.out.println("Need to do");
        return "studentInfo.xhtml";
    }

    public String addTeacher() {
        System.out.println("Need to do");
        return null;
    }

    /**
     * @return the studentname
     */
    public String getStudentname() {
        return studentname1;
    }

    /**
     * @param studentname the studentname to set
     */
    public void setStudentname(String studentname) {
        this.studentname1 = studentname;
    }

    /**
     * @return the teacher
     */
    public List<TeacherAdmin> getTeacherList() {
        System.out.println("Need to do");
        return teacherList;
    }

    /**
     * @param teacher the teacher to set
     */
    public void setTeacherList(List<TeacherAdmin> teacher) {
        this.teacherList = teacher;
    }

    /**
     * @return the classId
     */
    public String getClassId() {
        return schoolId;
    }

    /**
     * @param classId the classId to set
     */
    public void setClassId(String classId) {
        this.schoolId = classId;
    }

    /**
     * @return the ro
     */
    public int[] getRo() {
        myro = new int[]{0, 1, 2};
        return myro;
    }

    /**
     * @param ro the ro to set
     */
    public void setRo(int[] ro) {
        this.myro = ro;
    }

    /**
     * @return the roo
     */
    /**
     * @return the checkLogin
     */
    public TeaCheckLogin getCheckLogin() {
        return checkLogin;
    }

    /**
     * @param checkLogin the checkLogin to set
     */
    public void setCheckLogin(TeaCheckLogin checkLogin) {
        this.checkLogin = checkLogin;
    }

}
